var config = require('../../../config.js');
var request = require('../../../utils/request.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    optionType: 'add',//add or edit
    areaData: [],
    region: [0, 0, 0],
    areaRange: [],
    provinceRange: [],
    cityRange: [],
    countyRange: [],
    editAddress: {},//编辑地址的信息
    addressStr: '',
    is_default: false,
    consignee: '',
    mobile: '',
    address: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取 操作类型 新增或者修改
    var typet = options.type || 'add';
    var address = options.address || '';
    var addressInfo = {};
    if (address != '') {
      addressInfo = JSON.parse(options.address) || {};
      this.setData({
        optionType: typet,
        editAddress: addressInfo,
        addressStr: addressInfo.province + ' - ' + addressInfo.city + ' - ' + addressInfo.area,
        mobile: addressInfo.phone,
        is_default: addressInfo.isprimary == '1',
        consignee: addressInfo.user,
        address: addressInfo.address
      });
    } else {
      this.setData({
        optionType: typet,
      });
    }

    wx.showLoading({
      title: '加载数据...',
    });
    this.getArea()
      .then(data => {
        wx.hideLoading();
        this.setData({
          areaData: data.data.root
        })
        this.setProvinceData();
      }).catch(msg => {
        wx.hideLoading();
      });
  },

  
  /**
   * 设置省数据
   */
  setProvinceData: function () {
    this.setData({
      provinceRange: this.data.areaData,
    });

    if (this.data.optionType == 'add') {
      this.setCityData(0);
    } else {
      for (var i = 0; i < this.data.areaData.length; i++) {
        if (this.data.areaData[i].province == this.data.editAddress.province) {
          var reg = [];
          reg[0] = i;
          this.setData({
            region: reg
          });
          this.setCityData(i);
          console.log(this.data.region);
        }
      }
    }
  },

  /**
   * 设置市数据
   * provinceIndex 省的数据
   */
  setCityData: function (provinceIndex) {
    console.log('setCityData');

    var province = this.data.provinceRange[provinceIndex];
    var tempCitys = [];
    province.cities.map(item => {
      tempCitys.push(item)
    });

    this.setData({
      cityRange: tempCitys,
    });

    if (this.data.optionType == 'add') {
      this.setCountryData(0);
    } else {
      for (var j = 0; j < tempCitys.length; j++) {
        if (tempCitys[j].city == this.data.editAddress.city) {
          console.log(tempCitys[j]);
      
          var oldregion = this.data.region;
          oldregion[1] = j;
          this.setData({
            region: oldregion
          });
          this.setCountryData(j);
          console.log(this.data.region);
        }
      }
    }
  },

  /**
   * 设置区
   * cityIndex 市的数据
   */
  setCountryData: function (cityIndex) {
    console.log('setCountryData');

    var city = this.data.cityRange[cityIndex];
    var tempcounty = [];
    city.counties.map(item => {
      tempcounty.push(item)
    });

    this.setData({
      countyRange: tempcounty,
    });

    if (this.data.optionType != 'add') {
      for (var i = 0; i < tempcounty.length; i++) {
        if (this.data.editAddress.area == tempcounty[i].county) {
          console.log(tempcounty[i]);
          var oldregion = this.data.region;
          oldregion[2] = i;
          this.setData({
            region: oldregion
          });
          console.log(this.data.region);
        }
      }
    }
    this.setAreaRange();
  },


  setAreaRange: function () {
    let p = this.data.provinceRange.map(item => { return item.province });
    let c = this.data.cityRange.map(item => { return item.city });
    let co = this.data.countyRange.map(item => { return item.county });

    this.setData({
      areaRange: [p, c, co]
    });

  },
 
  bindRegionChange: function (event) {
    var value = event.detail.value;
    console.log(value);
    console.log(this.data.areaRange);
    var address = '';
    address += this.data.areaRange[0][value[0]] + ' - ';
    //市
    address += this.data.areaRange[1][value[1]] + ' - ';
    //县
    address += this.data.areaRange[2][value[2]];

    this.setData({
      region: value,
      addressStr: address
    });
  },

  bindCloumnChange: function (e) {
    var column = e.detail.column;
    var value = e.detail.value;

    if (column == 0) {
      //省变了
      this.setCityData(value);
    } else if (column == 1) {
      this.setCountryData(value)
    }
    this.setAreaRange();
  },

  /**
   * 获取城市数据
   */
  getArea: function () {
    return new Promise((resoleve, reject) => {
      var jsonUrl = 'https://image.hongheyu1688.com/miniapp/area.json';
      wx.request({
        url: jsonUrl,
        success: function (data) {
          resoleve(data);
        },
        fail: function (msg) {
          reject(msg);
        },
        complete: function () {

        }
      });
    })
  },


  checkboxChange: function (e) {
    var isdefault = e.detail.value.length > 0 ? true : false;
    this.setData({
      is_default: isdefault
    })
  },


  consigneeInput: function (event) {
    this.setData({
      consignee: event.detail.value
    })
  },

  mobileInput: function (event) {
    this.setData({
      mobile: event.detail.value
    })
  },
  addressInput: function (event) {
    this.setData({
      address: event.detail.value
    })
  },

  /**
   * 保存
   */
  onSaveTap: function () {
    if (!this.data.address || !this.data.consignee || !this.data.mobile || (this.data.city == 0)) {
      wx.showModal({
        title: '提示',
        content: '请正确填写每一项地址信息',
        showCancel: false,
      })
      return;
    }

    if (!(/^1[34578]\d{9}$/.test(this.data.mobile))) {
      wx.showModal({
        title: '提示',
        content: '电话号码有误',
        showCancel: false,
      })
      return;
    }

    var value = this.data.region;
    var params = {
      province: this.data.areaRange[0][value[0]],
      city: this.data.areaRange[1][value[1]],
      area: this.data.areaRange[2][value[2]],
      address: this.data.address,
      user: this.data.consignee,
      phone: this.data.mobile,
      isDefault: this.data.is_default ? 1 : 0
    }
    console.log(params);
    var url = '';
    if (this.data.optionType == 'add') {
      url = config.addAddressUrl;
    } else {
      url = config.upadteAddressUrl;
      params.id = this.data.editAddress.id;
    }
    console.log(params);
    wx.showLoading({
      title: '',
    })
    request.requestPost(url, params)
      .then(data => {
        wx.hideLoading();
        wx.showToast({
          title: '地址添加成功',
        });
        wx.navigateBack({});
      }).catch(msg => {
        wx.hideLoading();
        console.log(msg);
      })

  },

  onCancleTap: function (e) {
    wx.hideLoading();
    wx.navigateBack();
  },
})